import Koa from 'koa';
import Router from 'koa-router'
import bodyparser from 'koa-bodyparser'
import cors from '@koa/cors'
import { Sequelize, DataTypes } from 'sequelize'

let app = new Koa()
let router = new Router()
var port = 7070

let sequelize = new Sequelize('backoffice', 'root', 'Ye725601', {
    host: '8.152.214.221',
    dialect: "mysql"
})

let User = sequelize.define('users', {
    uname: {
        type: DataTypes.STRING
    },
    upassword: {
        type: DataTypes.STRING
    }
}, {
    timestamps: false
})

// await sequelize.sync({ force: true });

app.use(bodyparser());
app.use(cors())

router.get('/user', async (ctx) => {
    let inputAccount = ctx.request.query.account
    let inputPassword = ctx.request.query.password
    ctx.body = ''
    let tmpObj = await User.findOne({
        where: {
            uname: inputAccount
        }
    })
    console.log(tmpObj.dataValues.upassword);
    let dbPassword = tmpObj.dataValues.upassword
    if (!tmpObj) {
        ctx.status = 401 // 定义用户名错误状态码
    } else {
        if (dbPassword == inputPassword) {
            ctx.status = 200 // 定义密码正确状态码
        } else {
            ctx.status = 405 // 定义密码错误状态码
        }
    }
})

router.post('/user', async (ctx) => {
    ctx.body = ''
    let tmpObj = ctx.request.body
    var findAccount = tmpObj.uname;
    let findObj = await User.findOne({
        where: {
            uname: findAccount
        }
    })
    console.log(findObj);
    
    if (findObj) {
        ctx.status = 444
    } else {
        await User.create(tmpObj);
    }
})

app.use(router.routes())

app.listen(port, () => {
    console.log("Server is running : http://localhost:7070");

})